<template>
    <el-card v-loading="loading">
        <template #header>
            <div class="card-header">
                <div class="buttons">
                    <div class="mb-4">
                        <el-button type="primary" round @click="addNew">新增</el-button>
                        <el-button type="success" round @click="update">修改</el-button>
                        <el-button type="danger" round @click="handeleDelete">删除</el-button>
                        <el-button type="warning" round @click="toggleSelection()">清空选择</el-button>
                    </div>
                </div>
            </div>
        </template>
        <el-table ref="multipleTableRef" :data="tableData" row-key="id" @selection-change="handleSelectionChange"
            @row-click="handleRowChick" :tree-props="{ children: 'children' }">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="部门名" />
            <el-table-column label="状态" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.enabled" class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        @change="changeEnable(scope.row)" />
                </template>

            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
        </el-table>
    </el-card>


    <!-- 更新菜单表单 -->
    <el-drawer v-model="drawer_update" title="修改员工">
        <el-form ref="updateFormRef" style="max-width: 600px" :model="updateForm" :rules="updaterules"
            label-width="auto" class="demo-ruleForm" status-icon>
            <el-form-item label="名称" prop="name">
                <el-input v-model="updateForm.name" />
            </el-form-item>


            <el-form-item label="上级部门" prop="pid">
                <el-tree-select v-model="updateForm.pid" :data="optionsDept" check-strictly
                    @visible-change="getDeptOptions" :loading="loadingDept"
                    :props="{ children: 'children', label: 'name', value: 'id' }" style="width: 240px" />
            </el-form-item>



            <el-form-item>
                <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
                    提交
                </el-button>
                <el-button @click="resetUpdateForm(updateFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

    <!-- 新建菜单表单 -->
    <el-drawer v-model="drawer_new" title="新建员工">
        <el-form ref="newFormRef" style="max-width: 600px" :model="newForm" :rules="newrules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="名称" prop="name">
                <el-input v-model="newForm.name" />
            </el-form-item>
            <el-form-item label="上级部门" prop="pid">
                <el-tree-select v-model="newForm.pid" :data="optionsDept" check-strictly
                    @visible-change="getDeptOptions" :loading="loadingDept"
                    :props="{ children: 'children', label: 'name', value: 'id' }" style="width: 240px" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitNewForm(newFormRef)">
                    提交
                </el-button>
                <el-button @click="resetNewForm(newFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

</template>
<script lang="ts" setup>
import { reactive, ref, onBeforeMount } from 'vue'
import { ElTable, ElTree, ElNotification } from 'element-plus'
import { getDept, createDept, deleteDept, updateDept } from '@/api/dept';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

interface Dept {
    id: string
    name: string
    createTime: String
    children?: Array<object>
    pid: String
    enabled: boolean
    leaf: boolean
}
const drawer_new = ref(false)
const drawer_update = ref(false)

const loading = ref(false)
const loadingDept = ref(false)

const tableData: Dept[] = reactive([

])
const optionsDept = ref([])
const getDeptOptions = async () => {
    loadingDept.value = true
    optionsDept.value.length = 0;
    const res = await getDept()
    if (res != null) {
        if (res.status == "200") {
            // ElNotification({
            //     title: "Success",
            //     type: "success",
            //     message: "成功"
            // }
            console.log("获取成功")
            const { data } = res
            treeHandlerOp(data)
            loadingDept.value = false

        } else {
            console.log("获取失败", res.status)
        }
    } else {
        console.log("请求失败")
    }
    console.log(optionsDept)

}

const treeHandlerOp = (datas) => {
    optionsDept.value.length = 0
    optionsDept.value.push({
        name: "顶级部门(无上级部门)",
        createTime: "",
        enabled: true,
        id: "-1",
        pid: '-1',
        leaf: true
    })
    for (let i = 0; i < datas.length; i++) {
        if (datas[i].pid == null) {
            optionsDept.value.push({
                name: datas[i].name,
                createTime: datas[i].name,
                enabled: datas[i].enabled,
                id: datas[i].id,
                pid: '-1',
                leaf: datas[i].leaf
            })
            datas.splice(i, 1)
            i--
        }

    }
    optionsDept.value.forEach(x => treeBuilder(x, datas))
}


const changeEnable = async (target) => {
    let temp: Dept = {
        name: target.username,
        enabled: target.enabled,
        createTime: target.createTime,
        id: target.id,
        children: target.children,
        pid: target.pid,
        leaf: target.leaf,
    }
    const res = await updateDept(temp);
    if (res.status == '204') {
        ElNotification({
            title: "Success",
            type: "success",
            message: "用户状态更改成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "用户状态更改失败"
        })
        temp = tableData.find(x => x.id == temp.id)
        temp.enabled = !temp.enabled
    }
}

const addNew = () => {
    drawer_new.value = true
}

const update = () => {
    console.log(multipleSelection.value)
    if (multipleSelection.value.length != 1) {
        ElNotification({
            title: "Warning",
            message: "请选择单个选项",
            type: "warning"
        })
    } else {
        drawer_update.value = true;
    }
}

const handeleDelete = async () => {
    if (multipleSelection.value.length <= 0) {
        ElNotification({
            title: "Warning",
            type: "warning",
            message: "请选择删除对象"
        })
        return
    }
    let deleteArray = []
    for (let i of multipleSelection.value) {
        if (i.id == '1') {
            ElNotification({
                title: "Warning",
                type: "warning",
                message: "不能删除超级管理员"
            })
            return
        }
        deleteArray.push(i.id)
    }
    loading.value = true;
    const res = await deleteDept(deleteArray);
    if (res.status == "200") {
        getDeptIm();
        ElNotification({
            title: "Success",
            type: "success",
            message: "删除成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "删除失败"
        })
    }
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Dept[]>([])
const toggleSelection = (rows?: Dept[]) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }

}

const handleRowChick = (row) => {
    const selected = multipleSelection.value.some((item) => item.id === row.id)
    if (!selected) {
        multipleSelection.value.push(row)
        multipleTableRef.value.toggleRowSelection(row, true)
    } else {
        const finArr = multipleSelection.value.filter((item) => {
            return item.id !== row.id
        })
        multipleSelection.value = finArr
        multipleTableRef.value.toggleRowSelection(row, false)
    }

}

const handleSelectionChange = (val: Dept[]) => {
    multipleSelection.value = val
}

const getDeptIm = async () => {
    loading.value = true
    tableData.length = 0;
    tableData.push({
        name: "顶级部门(无上级部门)",
        createTime: "",
        enabled: true,
        id: "-1",
        pid: '-1',
        leaf: true
    })
    const res = await getDept()
    if (res != null) {
        if (res.status == "200") {
            // ElNotification({
            //     title: "Success",
            //     type: "success",
            //     message: "成功"
            // }
            console.log("获取成功")
            const { data } = res
            treeHandler(data)

        } else {
            console.log("获取失败", res.status)
        }
    } else {
        console.log("请求失败")
    }
    loading.value = false
}

const treeHandler = (datas) => {
    tableData.length = 0
    for (let i = 0; i < datas.length; i++) {
        if (datas[i].pid == null) {
            tableData.push({
                name: datas[i].name,
                createTime: datas[i].createTime,
                enabled: datas[i].enabled,
                id: datas[i].id,
                pid: '-1',
                leaf: datas[i].leaf
            })
            datas.splice(i, 1)
            i--
        }

    }
    tableData.forEach(x => treeBuilder(x, datas))
    console.log(tableData)
}

const treeBuilder = (target, datas) => {
    if (!target.leaf) {
        for (let i = 0; i < datas.length; i++) {
            if (datas[i].pid == target.id) {
                const deptTemp: Dept = {
                    name: datas[i].name,
                    createTime: datas[i].createTime,
                    id: datas[i].id,
                    enabled: datas[i].enabled,
                    pid: datas[i].pid,
                    leaf: datas[i].leaf
                }
                if (target.children != null) {
                    target.children.push(deptTemp)
                } else {

                    target.children = [deptTemp]
                }
                datas.splice(i, 1)
                i--
                if (!deptTemp.leaf) {
                    treeBuilder(deptTemp, datas)
                }
            }
        }
    } else {
        target.children = []
    }
}
const newFormRef = ref<FormInstance>()
const newForm = reactive<Dept>({
    id: '',
    name: '',
    pid: '',
    createTime: '',
    children: [],
    enabled: true,
    leaf: true
})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<Dept>({
    id: '',
    name: '',
    pid: '',
    createTime: '',
    children: [],
    enabled: true,
    leaf: true
})

const newrules = reactive<FormRules<Dept>>({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
    pid: [
        { required: true, message: '请选择上级部门', trigger: 'blur' },
    ],
})

const updaterules = reactive<FormRules<Dept>>({
    name: [
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
})

const submitUpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            let temp = {}
            console.log(updateForm.pid)
            if (updateForm.pid == '-1' || updateForm.pid == null) {
                temp = {
                    id: multipleSelection.value[0].id,
                    name: updateForm.name || multipleSelection.value[0].name,
                    enabled: multipleSelection.value[0].enabled
                }
            } else {
                temp = {
                    id: multipleSelection.value[0].id,
                    name: updateForm.name || multipleSelection.value[0].name,
                    pid: updateForm.pid || multipleSelection.value[0].pid,
                    enabled: multipleSelection.value[0].enabled
                }
            }
            const res = await updateDept(temp);
            if (res.status == '204') {
                ElNotification({
                    title: 'Success',
                    message: "修改成功",
                    type: 'success'
                })
                getDeptIm()
                drawer_update.value = false
            } else {
                console.log(res)
                ElNotification({
                    title: 'Error',
                    message: res.data.message,
                    type: 'error'
                })
            }
        } else {
            console.log('error submit!', fields)
        }
        loading.value = false
    })
}

const resetUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitNewForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            let temp = {}
            if (newForm.pid == '-1') {
                temp = {
                    name: newForm.name,
                    pid: '',
                    enabled: true
                }
            } else {
                temp = {
                    name: newForm.name,
                    pid: newForm.pid,
                    enabled: true
                }
            }
            const res = await createDept(temp);
            if (res.status == '201') {
                ElNotification({
                    title: "Success",
                    type: "success",
                    message: "添加成功"
                })
                drawer_new.value = false
                getDeptIm()
            } else {
                ElNotification({
                    type: "error",
                    title: "Error",
                    message: '添加失败' + res.data.message
                })
                loading.value = false
            }
        }
        else {
            console.log('error submit!', fields)
            loading.value = false
        }
    })
}

const resetNewForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

onBeforeMount(() => {
    getDeptIm()
})
</script>

<style></style>